package com.ad.nbi.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

public class JsonUtil {
	private static File[] list;

	private static void init() {
		File dir = new File("mock");
		list = dir.listFiles();
	}

	private static File getFile(String clazz) {
		if (list == null) {
			init();
		}
		for (File file : list) {
			if (clazz.equals(file.getName())) {
				return file;
			}
		}
		return null;
	}

	public static Object get(Class clazz) {
		ObjectMapper mapper = new ObjectMapper();
		File file = getFile(clazz.getName());
		Object obj = new Object();
		try {
			obj = mapper.readValue(file, clazz);
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return obj;
	}

	public static List getList(Class clazz, TypeReference type) {
		ObjectMapper mapper = new ObjectMapper();
		File file = getFile(clazz.getName());
		List list = new ArrayList();
		try {
			list = mapper.readValue(file, type);
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
}
